﻿//-----------------------------------------------------------------------
// <copyright file="Queries.cs" company="Microsoft Corporation">
//     Copyright Microsoft Corporation. All Rights Reserved. This code released under the terms of the Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.) This is sample code only, do not use in production environments.
// </copyright>
//-----------------------------------------------------------------------
namespace VisualStudioOnlineOData
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using System.Xml.Linq;

    /// <summary>
    ///
    /// </summary>
    public static class Queries
    {
        /// <summary>
        /// Gets the queries asynchronous.
        /// </summary>
        /// <param name="credentials">The credentials.</param>
        /// <param name="onSuccessfulResult">The on successful result.</param>
        /// <returns></returns>
        public static async Task<IEnumerable<Models.Query>> GetQueriesAsync(Credentials credentials, Action<XDocument> onSuccessfulResult = null)
        {
            var result = new List<Models.Query>();
            await GetQueriesAsync(credentials, "https://tfsodata.visualstudio.com/DefaultCollection/Queries", result);
            if (onSuccessfulResult != null)
            {
                var xdocument = new XDocument();
                var root = new XElement("root");
                foreach (var query in result)
                {
                    root.Add(query.ToXML());
                }

                xdocument.Add(root);

                onSuccessfulResult(xdocument);
            }

            return result;
        }

        private static async Task GetQueriesAsync(Credentials credentials, string url, IList<Models.Query> result)
        {
            var httpGet = await Http.GetAsync(new Uri(url), credentials);
            if (httpGet == null)
            {
                return;
            }

            var httpResult = XMLDeserialiser.DeserialiseFromString<Models.Queries>(httpGet);
            if (httpResult == null || httpResult.Entry == null)
            {
                return;
            }

            foreach (var item in httpResult.Entry)
            {
                result.Add(item);
            }

            var next = httpResult.Link.FirstOrDefault(_ => _.Rel == "next");
            if (next != null)
            {
                await GetQueriesAsync(credentials, next.href, result);
            }
        }
    }
}